package com.example.uniapp.db;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.example.uniapp.R;
import com.example.uniapp.utils.FileImgUtils;

/**
 * 连接数据库
 */
public class DBUtils extends SQLiteOpenHelper {

    private static final int version=11; //版本号,更改表结构就+1
    private static final String databaseName="db_takeaway.db"; //数据库名称必须以db结尾
    private Context context;

    public static SQLiteDatabase con; //链接数据库的链接，通过它操作数据库

    public DBUtils(Context context) {
        super(context, databaseName, null, version, null);
        this.context=context;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        //创建各个表
        db.execSQL("PRAGMA foreign_keys=false"); //先关闭外键关联，防止先创建子表报错

        //创建用户表
        db.execSQL("drop table if exists users"); //如果该表存在就删除

        //该表包括了用户id，密码，用户头像三部分
        db.execSQL("create table users(" +
                "user_id varchar(20) primary key," +
                "user_pwd varchar(20)," +
                "user_avator varchar(255))");

        //获取默认头像地址并保存
        String avatorPath = FileImgUtils.getImgName(); //获取图片存储路径
        FileImgUtils.saveSystemImgtoPath(context, R.drawable.default_avator, avatorPath);

        //加入默认用户数据
        db.execSQL("INSERT INTO users (user_id, user_pwd, user_avator)" +
                "VALUES (?, ?, ?)",
                new Object[]{"root", "123456", avatorPath});

        //创建食谱表
        db.execSQL("drop table if exists cookbook"); //如果该表存在就删除

        //该表包括了食谱id，用户id，食谱名，食谱发布时间，食谱图片五部分
        db.execSQL("create table cookbook(" +
                "cookbook_id varchar(20) primary key," +
                "user_id varchar(20)," +
                "cookbook_name varchar(20)," +
                "cookbook_release_time varchar(255)," +
                "cookbook_img varchar(255))");

        //创建食谱食材表
        db.execSQL("drop table if exists cookbookfood");

        //该表包括食谱id，食材名，食材数量三部分
        db.execSQL("create table cookbookfood(" +
                "cookbook_id varchar(20)," +
                "cookbook_food varchar(10)," +
                "cookbook_food_count varchar(10)," +
                "PRIMARY KEY (cookbook_id, cookbook_food))");

        //创建食谱制作步骤表
        db.execSQL("drop table if exists cookbookstep");

        //该表包括食谱id跟食谱步骤两部分
        db.execSQL("create table cookbookstep(" +
                "cookbook_id varchar(20)," +
                "cookbook_step varchar(255))");

        db.execSQL("PRAGMA foreign_keys=true");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int i, int i1) {
        onCreate(db);
    }
}
